﻿using Koala.Pro.Common;
using Newtonsoft.Json;
using System.Net;
using System.Text;
using System.Security.Cryptography;

namespace Koala.Pro.Helpers
{
    public class TranslationHelper
    {
        public static string Translate(string inputString, string from = "zh", string to = "en")
        {
            return BaiduTranslate(inputString, from, to);
        }

        private static string BaiduTranslate(string inputString, string from = "zh", string to = "en")
        {
            string text = "";
            string text2 = "20180502000152401";
            string value = "rb0KjwtPfZccZinVAi6J";
            int num = 0;
            StringBuilder stringBuilder = new StringBuilder();
            string empty = string.Empty;
            stringBuilder.Append(text2);
            stringBuilder.Append(inputString);
            stringBuilder.Append(num);
            stringBuilder.Append(value);
            byte[] bytes = Encoding.UTF8.GetBytes(stringBuilder.ToString());
            empty = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(bytes)).Replace("-", "");
            empty = empty.ToLower();
            try
            {
                WebClient webClient = new WebClient();
                string address = $"http://api.fanyi.baidu.com/api/trans/vip/translate?q={inputString}&from=zh&to=en&appid={text2}&salt={num}&sign={empty}";
                byte[] bytes2 = webClient.DownloadData(address);
                TranslationJson translationJson = JsonConvert.DeserializeObject<TranslationJson>(Encoding.UTF8.GetString(bytes2));
                if (translationJson != null)
                {
                    text = translationJson.trans_result[0].dst;
                    text = StringUtil.ToProperCase(text);
                }
            }
            catch (Exception)
            {
            }
            return text;
        }
    }
}

internal class TranslationJson
{
    public string from { get; set; }

    public string to { get; set; }

    public List<TranslationResult> trans_result { get; set; }
}

internal class TranslationResult
{
    public string src { get; set; }

    public string dst { get; set; }
}